<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2>登录</h2>
      </template>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <div class="login-options">
          <el-checkbox v-model="loginForm.rememberPassword">记住密码</el-checkbox>
          <el-checkbox v-model="loginForm.autoLogin">自动登录</el-checkbox>
        </div>
        <el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            class="login-button"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { login } from '@/api/auth'

const router = useRouter()
const loading = ref(false)
const loginFormRef = ref(null)

const loginForm = reactive({
  username: 'admin',
  password: 'admin',
  rememberPassword: false,
  autoLogin: false
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 从本地存储加载登录信息
onMounted(() => {
  const savedLoginInfo = JSON.parse(localStorage.getItem('loginInfo') || '{}')
  if (savedLoginInfo.rememberPassword) {
    loginForm.username = savedLoginInfo.username || ''
    loginForm.password = savedLoginInfo.password || ''
    loginForm.rememberPassword = true
    loginForm.autoLogin = savedLoginInfo.autoLogin || false
    
    // 如果设置了自动登录，自动执行登录
    if (savedLoginInfo.autoLogin) {
      handleLogin()
    }
  }
})

// 保存登录信息到本地存储
const saveLoginInfo = () => {
  if (loginForm.rememberPassword) {
    localStorage.setItem('loginInfo', JSON.stringify({
      username: loginForm.username,
      password: loginForm.password,
      rememberPassword: true,
      autoLogin: loginForm.autoLogin
    }))
  } else {
    localStorage.removeItem('loginInfo')
  }
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      console.log('正在发送登录请求...', {
        username: loginForm.username,
        password: loginForm.password
      })
      
      try {
        // 调用登录API
        const response = await login({
          username: loginForm.username,
          password: loginForm.password
        })
        
        console.log('登录API响应:', response)
        
        // 保存登录信息
        saveLoginInfo()
        
        // 根据后端API的实际响应格式获取token
        // 假设响应格式为 { code: 200, data: { token: 'xxx', user: {...} }, message: 'xxx' }
        const { data } = response.data
        
        if (data && data.token) {
          localStorage.setItem('token', data.token)
          
          // 如果响应中包含用户信息，也一并保存
          if (data.user) {
            localStorage.setItem('userInfo', JSON.stringify(data.user))
          }
          
          ElMessage.success('登录成功')
          router.push('/home')
        } else {
          ElMessage.error('登录失败：响应中没有找到token')
          console.error('响应数据异常:', response.data)
        }
      } catch (error) {
        console.error('登录失败, 详细错误:', error)
        
        // 显示详细错误信息
        if (error.response) {
          console.error('响应状态码:', error.response.status)
          console.error('响应数据:', error.response.data)
          ElMessage.error(error.response.data?.message || '登录失败，请检查用户名和密码')
        } else if (error.request) {
          console.error('请求已发送但未收到响应')
          ElMessage.error('服务器无响应，请检查网络连接')
        } else {
          console.error('请求配置错误:', error.message)
          ElMessage.error(`请求错误: ${error.message}`)
        }
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
  max-width: 90%;
}

:deep(.el-card__header) {
  text-align: center;
  padding: 15px;
  font-size: 20px;
}

:deep(.el-card__body) {
  padding: 30px 20px;
}

h2 {
  margin: 0;
  color: #409EFF;
}

.login-options {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.login-button {
  width: 100%;
}
</style>
